import pickle

from PyQt5.QtCore import QStringListModel
from PyQt5 import QtCore,QtGui
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QPixmap
from PyQt5.QtWidgets import QTableWidgetItem

import Motion_Capture

"""视频"""
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog

import WriteRead
import data_struct
from UI.Qt_Page.MainPage import Ui_MainWindow as Main_UI # Main界面
from UI.Qt_Page.PPTPage import Ui_MainWindow as PPT_UI # b界面的库
from UI.Qt_Page.NewPlan import Ui_MainWindow as NewPlan_UI # b界面的库
from UI.Qt_Page.PlanInfoPage import Ui_MainWindow as PlanInfo_UI # 每个计划详情的页面
from UI.Qt_Page.MotionCapturePage import Ui_MainWindow as MotionCapture_UI # 动作捕捉页面


"""游戏相关"""
from UI.Qt_Page.GamePage import Ui_MainWindow as Game_UI # 游戏模式页面


import os
import PPTRun
from Pose import Draw_Pose
import New_Action_Record
import sys
from PyQt5 import QtCore, QtWidgets, QtCore

# 主窗口
class HelloWindow(QtWidgets.QMainWindow, Main_UI):
    switch_window1 = QtCore.pyqtSignal() # 跳转ppt信号
    switch_window2=QtCore.pyqtSignal()#跳转game页面
    switch_window3=QtCore.pyqtSignal()#跳转动作捕捉页面


    def __init__(self):
        super(HelloWindow, self).__init__()
        self.setupUi(self)
        self.PPTButton1.clicked.connect(self.goPPT)
        self.Gameb.clicked.connect(self.goGame)
        self.MCb.clicked.connect(self.goMC)

        """按钮贴图"""
        self.PPTButton1.setIcon(QtGui.QIcon("UI/Pic/会议圆桌图.jpg"))

        self.Gameb.setStyleSheet("QPushButton{border-image: url(UI/Pic/游戏手柄.bmp)}")
        self.pushButton_4.setStyleSheet("QPushButton{border-image: url(UI/Pic/关于我们.bmp)}")
        self.MCb.setStyleSheet("QPushButton{border-image: url(UI/Pic/动作捕捉.bmp)}")

        png = QPixmap('UI/Pic/两个手.jpeg')
        self.label_4.setPixmap(png)
        # 图片自适应窗口大小
        self.label_4.setScaledContents(True)

        png = QPixmap('UI/Pic/标志.png')
        self.label_12.setPixmap(png)
        # 图片自适应窗口大小
        self.label_12.setScaledContents(True)

    def goPPT(self):
        self.switch_window1.emit()
    def goGame(self):
        self.switch_window2.emit()
    def goMC(self):
        self.switch_window3.emit()


# 登录窗口
class PPTWindow(QtWidgets.QMainWindow, PPT_UI):
    """PPTPage"""
    switch_window2 = QtCore.pyqtSignal()  # 返回Main信号
    switch_window3 = QtCore.pyqtSignal()  # 跳转NewPlan页
    switch_window6=QtCore.pyqtSignal()  # 跳转PlanInfo页
    Plan_Name=0
    Plan_Path="F:\\project\\Gesture_rec\\PPT_PLAN\\"


    def __init__(self):
        super(PPTWindow, self).__init__()
        self.setupUi(self)

        """返回首页"""
        self.BackMain.clicked.connect(self.goMain)

        """会议系统运行"""
        self.PPTRUNbt.clicked.connect(self.PPTRUN)

        """创建方案按钮"""
        self.CreatPLANb.clicked.connect(self.goNewPlan)

        """跳转PlaInfo页"""
        self.PLANinfob.clicked.connect(self.goPlanInfo)

        """贴图"""
        png = QPixmap('UI/Pic/蓝色开会 发光.png')
        self.label_11.setPixmap(png)
        # 图片自适应窗口大小
        self.label_11.setScaledContents(True)

        png = QPixmap('UI/Pic/标志.png')
        self.label_4.setPixmap(png)
        # 图片自适应窗口大小
        self.label_4.setScaledContents(True)

        self.CreatPLANb.setStyleSheet("QPushButton{border-image: url(UI/Pic/会议按钮1 阴影.png)}")
        self.PPTRUNbt.setStyleSheet("QPushButton{border-image: url(UI/Pic/会议按钮2 阴影.png)}")
        self.PLANinfob.setStyleSheet("QPushButton{border-image: url(UI/Pic/会议按钮3 阴影.png)}")



    def Update_PPTChoiceCB(self):
        """下拉菜单初始化或更新"""
        for filename in os.listdir(r'F:\project\Gesture_rec\PPT_PLAN'):
            self.PPTChoiceCB.addItem(filename)
        self.PPTChoiceCB.currentIndexChanged.connect(self.Change_Plan)

    def goNewPlan(self):
        self.switch_window3.emit()

    def goMain(self):
        self.switch_window2.emit()

    def Change_Plan(self):
        index = self.PPTChoiceCB.currentIndex()
        text = self.PPTChoiceCB.itemText(index)
        text=text.split('.')[0]
        print("text",text)
        self.Plan_Name=text

    def PPTRUN(self):
        PPTRun.run(self.Plan_Name,self.Plan_Path)
    def goPlanInfo(self):
        self.switch_window6.emit()

class NewPlanWindow(QtWidgets.QMainWindow, NewPlan_UI):
    switch_window4 = QtCore.pyqtSignal()  # 返回PPTPage信号

    New_Action_List=[]#用来记录所有新动作的全部信息，目前最多存两个新动作
    New_Action=[]#用来记录新录制的动作的坐标序列

    def __init__(self):
        super(NewPlanWindow, self).__init__()
        self.setupUi(self)


        """现有动作表格"""
        ActionList=['手掌抬起','手掌向左挥动', '手掌向右挥动', '握拳', '食指向上',
                       '三指向上','OK形状三指向上','拇指竖起','','']#动作放在这
        OrderList=['手掌模式启动','向右翻页', '向左翻页', 'PPT关闭', '指尖模式开启',
                       '荧光笔','红笔','橡皮','','']


        """动作表格（新）"""

        #1：创建8行
        for row in range(8):
            self.Actiontable.insertRow(row)

        #2:添加数据
        for row in range(8):
            item = QTableWidgetItem()
            item.setText(ActionList[row])
            self.Actiontable.setItem(row,0,item)

        for row in range(8):
            item = QTableWidgetItem()
            item.setText(OrderList[row])
            self.Actiontable.setItem(row, 1, item)


        """新增动作表单提交"""
        self.ActionSubmitb.clicked.connect(self.Action_Submit)

        """录制动作按钮"""
        self.RecordActionb.clicked.connect(self.Record_Action)

        """方案提交按钮"""
        self.PlanSubmitb.clicked.connect(self.PlanSubmit)

        """返回按钮（返回PPTPage）"""
        self.Backb.clicked.connect(self.BackPPTPage)


        """贴图"""
        png = QPixmap('UI/Pic/标志.png')
        self.label_12.setPixmap(png)
        # 图片自适应窗口大小
        self.label_12.setScaledContents(True)

    def BackPPTPage(self):
        self.switch_window4.emit()

    def Record_Action(self):
        self.New_Action=New_Action_Record.Record()

    def PlanSubmit(self):
        Data=data_struct.Write_Data()

        Plan_Name=self.PlanNamele.text().split('.')[0]#方案名
        for i in range(len(self.New_Action_List)):
            if self.New_Action_List[i][2]=='E':
                Data.CLEAR_ALL_NAME=self.New_Action_List[i][0]
                Data.CLEAR_ALL_MEAN=self.New_Action_List[i][1]
                Data.CLEAR_ALL_STD = self.New_Action_List[i][3]


            if self.New_Action_List[i][2]=='ctrl+R':
                Data.WATERCOLOR_PEN_NAME=self.New_Action_List[i][0]
                Data.WATERCOLOR_PEN_MEAN=self.New_Action_List[i][1]
                Data.WATERCOLOR_PEN_STD=self.New_Action_List[i][3]

        """看Data写的对不对"""
        Data.print_Data()

        """点提交发射返回PPT页的信号"""
        self.switch_window4.emit()

        #1:存两个新动作及记录信息
        WriteRead.Write_TXT(Plan_Name,"F:\\project\\Gesture_rec\\PPT_PLAN\\",Data)


    def Action_Submit(self):
        #1:获取文本信息
        Action_Name=self.ActionNamele.text()#手势名称
        Action_Mean=self.Actionmeanle_2.text()#手势描述
        Keyboard=self.Keyboardle.text()#触发的按键
        Action_Lm=self.New_Action#手势坐标序列


        #3:更新动作表格
        row_cnt = self.Actiontable.rowCount()  # 返回当前行数（尾部）
        self.Actiontable.insertRow(row_cnt)

        item = QTableWidgetItem()
        item.setText(Action_Name)
        self.Actiontable.setItem(row_cnt, 0, item)

        item = QTableWidgetItem()
        item.setText(Action_Mean)
        self.Actiontable.setItem(row_cnt, 1, item)

        #4:新增动作到这个window的New_Action_List暂存，等待方案提交
        temp=[]
        temp.append(Action_Name)#动作名称:手势六
        temp.append(Action_Mean)#命令动作：清屏
        temp.append(Keyboard)
        temp.append(Action_Lm)
        self.New_Action_List.append(temp)


class PlanInfoWindow(QtWidgets.QMainWindow, PlanInfo_UI):
    switch_window5=QtCore.pyqtSignal()#返回PPTpage信号
    def __init__(self):
        super(PlanInfoWindow, self).__init__()
        self.setupUi(self)

        self.Backb.clicked.connect(self.back_ppt)

        """贴图"""
        png = QPixmap('UI/Pic/6个开会图.png')
        self.label_3.setPixmap(png)
        # 图片自适应窗口大小
        self.label_3.setScaledContents(True)

        png = QPixmap('UI/Pic/标志.png')
        self.label_12.setPixmap(png)
        # 图片自适应窗口大小
        self.label_12.setScaledContents(True)

    def back_ppt(self):
        self.switch_window5.emit()

    def createtable(self,PlanName):
        self.PLActiontable.setRowCount(0)
        self.PLActiontable.clearContents()

        """默认动作"""
        """现有动作表格"""
        ActionList = ['手掌抬起', '手掌向左挥动', '手掌向右挥动', '握拳', '食指向上',
                      '三指向上', 'OK形状三指向上', '拇指竖起', '', '']  # 动作放在这
        OrderList = ['手掌模式启动', '向右翻页', '向左翻页', 'PPT关闭', '指尖模式开启',
                     '荧光笔', '红笔', '橡皮', '', '']

        """动作表格（新）"""

        # 1：创建8行
        for row in range(8):
            self.PLActiontable.insertRow(row)

        # 2:添加数据
        for row in range(8):
            item = QTableWidgetItem()
            item.setText(ActionList[row])
            self.PLActiontable.setItem(row, 0, item)
        for row in range(8):
            item = QTableWidgetItem()
            item.setText(OrderList[row])
            self.PLActiontable.setItem(row, 1, item)

        """自定义动作"""
        file = open("F:\\project\\Gesture_rec\\PPT_PLAN\\" + PlanName + ".txt", 'rb')
        Data = pickle.load(file)
        Data.print_Data()

        if Data.WATERCOLOR_PEN_STD != []:
            row_cnt = self.PLActiontable.rowCount()  # 返回当前行数（尾部）
            self.PLActiontable.insertRow(row_cnt)

            item = QTableWidgetItem()
            item.setText(Data.WATERCOLOR_PEN_NAME)
            self.PLActiontable.setItem(row_cnt, 0, item)

            item = QTableWidgetItem()
            item.setText(Data.WATERCOLOR_PEN_MEAN)
            self.PLActiontable.setItem(row_cnt, 1, item)

        if Data.CLEAR_ALL_STD != []:
            row_cnt = self.PLActiontable.rowCount()  # 返回当前行数（尾部）
            self.PLActiontable.insertRow(row_cnt)

            item = QTableWidgetItem()
            item.setText(Data.CLEAR_ALL_NAME)
            self.PLActiontable.setItem(row_cnt, 0, item)

            item = QTableWidgetItem()
            item.setText(Data.CLEAR_ALL_MEAN)
            self.PLActiontable.setItem(row_cnt, 1, item)

"""游戏相关的页面"""
class GamePageWindow(QtWidgets.QMainWindow, Game_UI):
    switch_window1 = QtCore.pyqtSignal()  # 返mainpage信号
    def __init__(self):
        super(GamePageWindow, self).__init__()
        self.setupUi(self)
        self.Bodyb.clicked.connect(self.runPose)
        self.Mouseb.clicked.connect(self.runMouse)
        self.BackMain.clicked.connect(self.backmain)

        """贴图"""
        png = QPixmap('UI/Pic/标志.png')
        self.label_12.setPixmap(png)
        # 图片自适应窗口大小
        self.label_12.setScaledContents(True)

        png = QPixmap('UI/Pic/中年男人打游戏 有字.bmp')
        self.label_4.setPixmap(png)
        # 图片自适应窗口大小
        self.label_4.setScaledContents(True)

        self.Bodyb.setStyleSheet("QPushButton{border-image: url(UI/Pic/手柄 阴影.png)}")
        self.Mouseb.setStyleSheet("QPushButton{border-image: url(UI/Pic/鼠标.png)}")


    def runPose(self):
        Draw_Pose.run_Pose()
    def runMouse(self):
        PPTRun.run("自定义方案2", "F:\\project\\Gesture_rec\\PPT_PLAN\\")
    def backmain(self):
        self.switch_window1.emit()

class MotionCaptureWindow(QtWidgets.QMainWindow,MotionCapture_UI):
    switch_window1 = QtCore.pyqtSignal()  # 返mainpage信号

    file_path=""#原视频文件路径
    file_save_path=""#脚本文件保存位置，例如 F:/迅雷下载
    file_save_name=""#脚本文件名称,例如 xxx.ms

    def __init__(self):
        super(MotionCaptureWindow, self).__init__()
        self.setupUi(self)

        """播放器相关"""
        # 播放器
        self.player = QMediaPlayer()
        self.player.setVideoOutput(self.video1)

        # 打开要播放文件的按钮
        self.btn_open.clicked.connect(self.openVideoFile)
        # 播放
        self.btn_play.clicked.connect(self.playVideo)  # play
        # 暂停
        self.btn_stop.clicked.connect(self.pauseVideo)  # pause

        """生成动捕脚本按钮"""
        self.createscriptb.clicked.connect(self.createscript)
        """选择动捕脚本保存位置按钮"""
        self.savepathb.clicked.connect(self.getsavepath)

        """返回首页按钮"""
        self.BackMain.clicked.connect(self.backmain)

        """贴图"""
        png = QPixmap('UI/Pic/标志.png')
        self.label_12.setPixmap(png)
        # 图片自适应窗口大小
        self.label_12.setScaledContents(True)

        self.btn_play.setStyleSheet("QPushButton{border-image: url(UI/Pic/播放.bmp)}")
        self.btn_stop.setStyleSheet("QPushButton{border-image: url(UI/Pic/暂停.bmp)}")

    def openVideoFile(self):

        URL=QFileDialog.getOpenFileUrl()[0]
        path=URL.toString()
        path=path[path.rfind("file:///"):][8:]
        print("path",path)
        self.file_path=path

        self.player.setMedia(QMediaContent(URL))
        self.player.play()

        print(self.player.availableMetaData())

    def playVideo(self):
        self.player.play()

    def pauseVideo(self):
        self.player.pause()

    def choosefile(self):

        #print(QMediaContent(QFileDialog.getOpenFileUrl()[0]))
        file_name = QtWidgets.QFileDialog.getOpenFileName(self, "open file dialog", "F:/","mp4 files(*.mp4)")
        print(file_name[0])
        self.file_path=file_name[0]

    def getsavepath(self):
        options = QFileDialog.Options()
        self.file_save_path= QtWidgets.QFileDialog.getExistingDirectory(None,"选取文件夹","F:/")
        print(self.file_save_path)

    def createscript(self):
        self.file_save_name=self.scriptnamele.text()
        print(self.file_save_name)

        """调用动捕函数"""
        Motion_Capture.MC_run(self.file_path,self.file_save_path,self.file_save_name)

    def backmain(self):
        self.switch_window1.emit()

class Controller:

    def __init__(self):
        self.hello=HelloWindow()
        self.PPT=PPTWindow()
        self.NewPlan=NewPlanWindow()
        self.PlanInfo=PlanInfoWindow()
        self.Game=GamePageWindow()
        self.MotionCapture=MotionCaptureWindow()

    def Close_All(self,str):
        """
        关闭全部窗口
        """
        if self.hello.isVisible()==True and str!="hello":
            self.hello.close()
        if self.PPT.isVisible()==True and str!="PPT":
            self.PPT.close()
        if self.NewPlan.isVisible()==True and str!="NewPlan":
            self.NewPlan.close()
        if self.MotionCapture.isVisible()==True and str!="MotionCapture":
            self.MotionCapture.close()
        if self.Game.isVisible()==True and str!="Game":
            self.Game.close()

    # 跳转到 hello 窗口
    def show_hello(self):

        #self.Close_All()
        self.hello.switch_window1.connect(self.show_PPT)
        self.hello.switch_window2.connect(self.show_GamePage)
        self.hello.switch_window3.connect(self.show_MotionCapturePage)

        self.hello.show()
        self.Close_All("hello")


    def show_PPT(self):

        """清空旧方案CB内容，并更新"""
        self.PPT.PPTChoiceCB.clear()
        self.PPT.Update_PPTChoiceCB()
        self.PPT.switch_window2.connect(self.show_hello)#返回Main
        self.PPT.switch_window3.connect(self.show_NewPlan)  # 去newplan的信号绑定
        self.PPT.switch_window6.connect(self.show_PlanInfo)

        self.PPT.show()
        self.Close_All("PPT")

    def show_NewPlan(self):
        self.Close_All("NewPlan")
        """绑定NewPlan页的信号"""
        self.NewPlan.switch_window4.connect(self.show_PPT)

        self.NewPlan.show()
        self.Close_All("NewPlan")

    def show_PlanInfo(self):
        Plan_Name=self.PPT.Plan_Name
        self.PlanInfo.createtable(Plan_Name)
        self.PlanInfo.switch_window5.connect(self.show_PPT)
        self.PlanInfo.show()
        self.Close_All("PlanInfo")

    def show_GamePage(self):

        self.Game.switch_window1.connect(self.show_hello)

        self.Game.show()
        self.Close_All("Game")

    def show_MotionCapturePage(self):

        self.MotionCapture.switch_window1.connect(self.show_hello)

        self.MotionCapture.show()
        self.Close_All("MotionCapture")



def main():
    app = QtWidgets.QApplication(sys.argv)
    controller = Controller() # 控制器实例

    """默认直接打开主页,如果想直接打开某页，把这个注释"""
    controller.show_hello() # 默认展示的是 hello 页面

    """如果想直接打开PPT页，把这个打开"""
    #controller.show_MotionCapturePage()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
